#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#     Filename @  question1.py
#       Author @  Huoty
#  Create date @  2015-05-29 14:02:17
#  Description @  
# *************************************************************

# Question: 使用for循环、while循环和递归写出3个函数来计算给定数列的总和。

# 给定数列
series = (54, 52, 12, 55, 77, 44, 41, 21, 21, 25, 65, 68, 89, 84, 51, 66, 31, 65, 16)

# for 
def sumbyfor(series):
    '''用 for 循环求一个数列的和'''
    sum = 0
    cnt = len(series)
    for index in range(cnt): # for循环主要用作序列的遍历
        sum += series[index]
    '''
    这里其实有一个简单的实现方法，我这样写只是采用了C语言的风格：
    for data in series
        sum += data
    '''

    return sum 

# while
def sumbywhile(series):
    '''用 while 循环求一个数列的和'''
    sum = 0
    cnt = len(series)
    i = 0
    while i < cnt:
        sum += series[i]
        i += 1

    return sum

# recursion
def sumbyrecursion(series, cnt):
    '''通过递归求一个序列的和'''
    index = cnt - 1

    if index == 0:
        return series[0]

    return series[index] + sumbyrecursion(series, index)

# Script starts from here

if __name__ == "__main__":
    print "原序列为：", series
    print "for 循环求和结果：", sumbyfor(series)
    print "while 循环求和结果：", sumbywhile(series)
    seqlen = len(series)
    print "递归求和结果：", sumbyrecursion(series, seqlen)
